﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace com.motoman.UDP
{
/**
 *
 * @author Johnathan Pretorius
 */

    public class UDPcommand
    {

        IPAddress ipaddress;
        int port;
        Socket sock;

        public UDPcommand(string ipaddress, int port)
        {
            this.ipaddress = IPAddress.Parse(ipaddress);
            this.sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sock.Connect(this.ipaddress, this.port);
        }

        public void UDPSend(String message)
        {

            try
            {
                byte[] bMessage = Encoding.ASCII.GetBytes(message);
                sock.Send(bMessage);
            }
            catch (Exception)
            {
                System.Windows.Forms.MessageBox.Show("Could not send message to barionet");
            }
        }

        public String UDPReceive()
        {
            String msgReceive = "";
            try
            {
                byte[] ReceiveBuffer = new byte[2048];

                sock.Receive(ReceiveBuffer);

                // Convert the contents to a string
                String msg = Encoding.ASCII.GetString(ReceiveBuffer);

            }
            catch (Exception e)
            {
                msgReceive = "UDP receive error : " + e.Message;
            }

            return msgReceive;
        }
    }
}